/*
 * Created on May 14, 2005
 *
 */
package org.mushroomdb.engine.operation.impl;

import java.util.Iterator;

import org.mushroomdb.engine.operation.AbstractBinaryRelationOperation;
import org.mushroomdb.engine.operation.RelationOperation;
import org.mushroomdb.engine.optimizer.RelationOperationVisitor;
import org.mushroomdb.executionplan.ExecutionPlanElement;
import org.mushroomdb.executionplan.ExecutionPlanElementImpl;
import org.mushroomdb.util.MultipleIterator;


/**
 * @author Matias
 *
 */
public class UnionOperation extends AbstractBinaryRelationOperation {

	/**
	 * @param leftRelationOperation
	 * @param rightRelationOperation
	 */
	public UnionOperation(RelationOperation leftRelationOperation, RelationOperation rightRelationOperation) {
		super(leftRelationOperation, rightRelationOperation);
	}

	/**
	 * @see org.mushroomdb.engine.operation.RelationOperation#execute()
	 */
	public Iterator execute() {
		Iterator firstIterator = leftRelationOperation.execute();
		Iterator secondIterator = rightRelationOperation.execute();
		
		return new MultipleIterator(firstIterator,secondIterator);
	}

	/**
	 * toString
	 */
	public String toString() {
		return "(" + this.leftRelationOperation.toString() + //$NON-NLS-1$
			" UNION ALL " + //$NON-NLS-1$
			this.rightRelationOperation + ")"; //$NON-NLS-1$
	}

	/**
	 * @see org.mushroomdb.engine.operation.RelationOperation#buildExecutionPlan()
	 */
	public ExecutionPlanElement buildExecutionPlan() {
		ExecutionPlanElementImpl executionPlan = new ExecutionPlanElementImpl("UNION"); //$NON-NLS-1$
		executionPlan.addChild(this.leftRelationOperation.buildExecutionPlan());
		executionPlan.addChild(this.rightRelationOperation.buildExecutionPlan());
		return executionPlan;
	}

	/**
	 * Agregado por Hache para optimizar
	 * @return
	 */
	public void accept(RelationOperationVisitor v) {
		v.visitUnion(this);
		this.getLeftRelationOperation().accept(v);
		this.getRightRelationOperation().accept(v);		
	}
}
